package com.qqt.csr.route.mq;

import com.qqt.csr.common.utils.CacheKeyUtil;
import com.qqt.csr.common.utils.JsonUtil;
import com.qqt.csr.common.utils.RedissonLockUtil;
import com.qqt.csr.im.entity.msg.Message;
import com.qqt.csr.im.service.EventMsgProducerService;
import com.qqt.csr.im.socketio.constants.EventsConstants;
import com.qqt.csr.route.entity.RouteTask;
import com.qqt.csr.route.service.DistributingRouteService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Author:
 * @Date:
 * @Description: im聊天消息处理
 **/
@Slf4j
@Service
@RocketMQMessageListener(
        consumerGroup = "${rocketmq.consumer.group}_route_im_msg",
        topic = EventMsgProducerService.MSG_CALLBACK_TOPIC,
        tlsEnable = "${rocketmq.consumer.tlsEnable}"
)
public class ImMessageHandlerListener implements RocketMQListener<String> {
    @Autowired
    private DistributingRouteService distributingRouteService;
    @Autowired
    private RedissonLockUtil redissonLockUtil;

    @Override
    public void onMessage(String data) {
        if (StringUtils.isBlank(data)) {
            return;
        }
        try {
            Message message = JsonUtil.toObject(data, Message.class);
            if(message == null){
                return;
            }
            String cacheKey = String.format(CacheKeyUtil.CsrRoute.IM_MSG_HANDLER_LOCK, message.getId());
            redissonLockUtil.distributedLock(() -> {
                message.convertContent();
                distributingRouteService.handleVisitorMsg(message);
            }, cacheKey, 0, 30, TimeUnit.MINUTES);
        } catch (Exception e) {
            log.error("im聊天消息处理失败！data:{}", data, e);
        }
    }

}
